package com.net.model.base;

import androidx.lifecycle.MutableLiveData;

import com.drug.lib.util.DLog;
import com.net.model.bean.BaseResponse;
import com.net.model.exception.ApiException;
import com.net.model.exception.ExceptionEngine;
import com.net.model.exception.ServerException;
import com.net.model.utils.Constant;

import io.reactivex.subscribers.ResourceSubscriber;

/**
 * 版权：周和权 版权所有
 *
 * @author zhouhequan
 * 版本：1.0
 * 创建日期：2021/11/12 or 21:50
 * 描述：---
 */
public class BaseHttpSubscriber<T> extends ResourceSubscriber<BaseResponse<T>> {
    private MutableLiveData<Resource<T>> liveData;

    public BaseHttpSubscriber() {
        liveData = new MutableLiveData();
    }

    public MutableLiveData<Resource<T>> get() {
        return liveData;
    }


    @Override
    protected void onStart() {
        super.onStart();
        liveData.postValue(Resource.loading());
    }


    @Override
    public void onNext(BaseResponse<T> baseResponse) {
        if ((baseResponse.getCode() == Constant.CODE_SUCCESS)) {
            liveData.postValue(Resource.response(baseResponse));
        } else {
            ServerException serverException = new ServerException(baseResponse.getCode(), baseResponse.getMessage());
            ApiException ex = ExceptionEngine.handleException(serverException);
            setApiException(ex);
        }
    }

    @Override
    public void onError(Throwable t) {
        t.printStackTrace();
        ApiException ex = ExceptionEngine.handleException(t);
        setApiException(ex);
    }

    @Override
    public void onComplete() {

    }

    /**
     * 初始化错误的dto
     *
     * @param ex
     */
    private void setApiException(ApiException ex) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setCode(ex.getCode());
        baseResponse.setMessage(ex.getMessage());
        DLog.e("请求异常 code:" + ex.getCode() + "  message:" + ex.getMessage());
        liveData.postValue(Resource.failure(baseResponse));
    }
}
